import json
import random
import uuid
from io import BytesIO
import random
from django.db.models import Q
from django.shortcuts import render
from django.utils.baseconv import base64
from django.core.serializers import serialize
from utils.image_code import check_code
# Create your views here.
from stw_app import models
from stw_app.models import Order, Code
from stw_app.models import UserInfo

from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from math import radians, sin, cos, sqrt, atan2
from datetime import datetime
import requests
from utils.tencent.sms import send_sms_single
from stw_Django import settings
import random
import uuid
from io import BytesIO
import random
from django.db.models import Q
from django.shortcuts import render
from django.utils.baseconv import base64
from django.core.serializers import serialize
from stw_Django import settings
from utils.image_code import check_code
from stw_app import models
from stw_app.models import Order, Code
from stw_app.models import UserInfo
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from math import radians, sin, cos, sqrt, atan2
from datetime import datetime
from utils.tencent.sms import send_sms_single
from django.contrib.auth import authenticate, login


def get_distance_score(distance):
    if distance <= 3:
        return 100
    elif (distance > 3) & (distance <= 5):
        return 100 - 5 * (distance - 3)
    elif (distance > 5) & (distance <= 10):
        return 90 - 8 * (distance - 5)
    elif (distance > 10) & (distance <= 30):
        return 50 - 2.5 * (distance - 10)
    else:
        return 0


def get_skill_score(skilled_work, work_type):
    if skilled_work == []:
        skilled_work = []
    k = 0
    for i in skilled_work:
        for j in work_type:
            if i == j:
                k += 1
    if k == 0:
        return 0
    elif k == 1:
        return 100
    elif k == 2:
        return 120
    elif k == 3:
        return 150


def get_wage_score(ideal_max_wage, ideal_min_wage, order_wage):
    if (ideal_min_wage == '') | (ideal_min_wage == ''):
        return 0
    if (order_wage >= ideal_min_wage) & (order_wage <= ideal_max_wage):
        return 100
    elif order_wage < ideal_min_wage:
        if ideal_min_wage - order_wage <= 100:
            return 100 - 0.5 * (ideal_min_wage - order_wage)
        elif (ideal_min_wage - order_wage > 100) & (ideal_min_wage - order_wage <= 200):
            return 50 - 0.25 * (ideal_min_wage - order_wage - 100)
        elif (ideal_min_wage - order_wage > 200) & (ideal_min_wage - order_wage <= 300):
            return 25 - 0.25 * (ideal_min_wage - order_wage - 200)
        else:
            return 0
    elif order_wage > ideal_max_wage:
        if order_wage - ideal_max_wage <= 100:
            return 100 - 0.5 * (order_wage - ideal_max_wage)
        elif (order_wage - ideal_max_wage > 100) & (order_wage - ideal_max_wage <= 200):
            return 50 - 0.25 * (order_wage - ideal_max_wage - 100)
        elif (order_wage - ideal_max_wage > 200) & (order_wage - ideal_max_wage <= 300):
            return 25 - 0.25 * (order_wage - ideal_max_wage - 200)
        else:
            return 0


def get_belief_score(score):
    return float(score) * 10


def get_all_score(ideal_max_wage, ideal_min_wage, skilled_work, distance, belief_score, wage, work_type):
    distance_score = get_distance_score(distance)
    wage_score = get_wage_score(ideal_max_wage, ideal_min_wage, wage)
    belief_score_score = get_belief_score(belief_score)
    skill_score = get_skill_score(skilled_work, work_type)
    all_score = distance_score * 0.3 + wage_score * 0.1 + skill_score * 0.3 + belief_score_score * 0.3
    return all_score


def give_recommend(request):
    if request.method == "POST":
        # user_id=int(request.POST.get('user_id'))
        user_id = 61
        place = ['天津市', '天津城区', '滨海新区']
        place_name = ''
        for i in place:
            place_name = place_name + i
        try:
            ideal_max_wage = float(UserInfo.objects.filter(id=user_id).first().highest_wage)
            idea_min_wage = float(UserInfo.objects.filter(id=user_id).first().lowest_wage)
        except:
            ideal_max_wage = ''
            idea_min_wage = ''
        skilled_work = []
        if str(UserInfo.objects.filter(id=user_id).first().career) != 'None':
            skilled_work.append(str(UserInfo.objects.filter(id=user_id).first().career))
        else:
            skilled_work = []
        # 换成用户的信息就行，依次是（最高预期工资，最低预期工资，擅长工作）
        latitude_2 = float(request.POST.get('latitude'))
        longitude_2 = float(request.POST.get('longitude'))
        data_list = []
        objects = Order.objects.all()
        for object in objects:
            latitude_1 = float(object.latitude)
            longitude_1 = float(object.longitude)
            distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
            distance = round(distance, 1)
            belief_score = UserInfo.objects.filter(id=object.customer_id).first().score
            province, city, district = get_order_p_c_d(longitude_1, latitude_1)
            data = {
                'id': object.id,
                'customer_id': object.customer_id,
                'real_worker_id': object.real_worker_id,
                'condition': object.condition,
                'price': float(object.price),
                'description': object.description,
                'type': object.type,
                'start_time': object.start_time,
                'end_time': object.end_time,
                'title': object.title,
                'date': object.date,
                'duration': object.duration,
                'score': object.score,
                'distance': distance,
                'requirement': object.requirement,
                'gender_requirement': object.gender_requirement,
                'belief_score': belief_score,
                'province': province,
                'city': city,
                'district': district,
            }
            data_list.append(data)
        print(ideal_max_wage)
        print(skilled_work)
        if (ideal_max_wage == '') & (skilled_work == []):
            return JsonResponse({'success': True, 'data': '信息不足'})
        for data in data_list:
            order_score = get_all_score(ideal_max_wage, idea_min_wage, skilled_work, data['distance'],
                                        float(data['belief_score']), float(data['price']), data['type'].split(','))
            data['order_score'] = order_score
        data_list = sorted(data_list, key=lambda x: x['order_score'], reverse=True)[:10]
        print(data_list)
        return JsonResponse({'success': True, 'data': data_list})
    else:
        return JsonResponse({'success': False})


def get_longitude_and_latitude(address):
    key = 'af5035a414311145ba566b1d4d9cbab0'
    output = 'json'
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    params = {
        'address': address,
        'key': key,
        'output': output}
    j = json.loads(requests.get(url, params).content)
    Longitude = str(j['geocodes'][1]['location']).split(',')[0]
    Latitude = str(j['geocodes'][1]['location']).split(',')[1]
    return Longitude, Latitude


def get_order_p_c_d(longitude, latitude):
    KEY = 'af5035a414311145ba566b1d4d9cbab0'
    LOCATION = str(longitude) + ',' + str(latitude)
    RADIUS = 3000
    OUTPUT = 'json'
    EX = 'all'
    POI_type = ''
    url = 'https://restapi.amap.com/v3/geocode/regeo'
    params = {
        "location": LOCATION,
        "output": OUTPUT,
        "key": KEY,
    }
    response = requests.get(url, params=params)
    # answer = json.loads(response.content)
    # 这种方式也可以
    answer = response.json()
    print(answer)
    province = answer['regeocode']['addressComponent']['province']
    some_provinces = ['北京市', '上海市', '重庆市', '天津市']
    if province in some_provinces:
        district = answer['regeocode']['addressComponent']['district']
        return province, '', district
    else:
        city = answer['regeocode']['addressComponent']['city']
        district = answer['regeocode']['addressComponent']['district']
        return province, city, district


def get_now_p_c():
    api_key = "af5035a414311145ba566b1d4d9cbab0"
    url = f"https://restapi.amap.com/v3/ip?key={api_key}"
    response = requests.get(url)
    data = response.json()
    some_provinces = ['北京市', '上海市', '重庆市', '天津市']
    if data["status"] == "1":
        province = data.get("province", "")
        if province in some_provinces:
            return province, ''
        city = data.get("city", "")
        return province, city
    else:
        print("请求失败或无数据")


# 获得省份列表
def get_provinces():
    url = 'https://restapi.amap.com/v3/config/district'
    params = {
        'key': 'af5035a414311145ba566b1d4d9cbab0',  # 请替换为您自己的高德地图API密钥
        'keywords': '中国',
        'subdistrict': 1,
        'extensions': 'base'
    }

    response = requests.get(url, params=params, verify=False)
    data = response.json()

    if data['status'] == '1' and data['count'] == '1':
        provinces = [province['name'] for province in data['districts'][0]['districts']]
        return provinces
    else:
        print('Failed to retrieve province data.')
        return []


# 获得城市列表
def get_cities(province):
    api_key = "af5035a414311145ba566b1d4d9cbab0"
    url = f"https://restapi.amap.com/v3/config/district?key={api_key}&keywords={province}&subdistrict=1&extensions=all&level=city"
    response = requests.get(url)
    data = response.json()
    cities = []
    if data["status"] == "1":
        districts = data.get("districts", [])
        for district in districts:
            citie = district.get("districts", [])
            for city in citie:
                city_name = city.get("name", "")
                cities.append(city_name)
        return cities
    else:
        print("请求失败或无数据")
        return []


# 获得区县列表
def get_districts(city):
    api_key = "af5035a414311145ba566b1d4d9cbab0"
    url = f"https://restapi.amap.com/v3/config/district?key={api_key}&keywords={city}&subdistrict=1&extensions=all"
    response = requests.get(url)
    data = response.json()
    districts = []
    if data["status"] == "1":
        districs = data.get("districts", [])
        for district in districs:
            if district["name"] == city:
                areas = district.get("districts", [])
                for area in areas:
                    area_name = area.get("name", "")
                    districts.append(area_name)
        return districts
    else:
        print("请求失败或无数据")
        return []


@csrf_exempt
def give_provinces(request):
    if request.method == "POST":
        provinces = get_provinces()
        return JsonResponse({'success': True, 'data': provinces})
    else:
        return JsonResponse({'success': False})


@csrf_exempt
def give_cities(request):
    if request.method == "POST":
        province = request.POST.get('province')
        if province != '':
            cities = get_cities(province)
            return JsonResponse({'success': True, 'data': cities})
        else:
            return JsonResponse({'success': True, 'data': []})
    else:
        return JsonResponse({'success': False})


@csrf_exempt
def give_districts(request):
    if request.method == "POST":
        city = request.POST.get('city')
        if city != '':
            districts = get_districts(city)
            return JsonResponse({'success': True, 'data': districts})
        else:
            return JsonResponse({'success': True, 'data': []})
    else:
        return JsonResponse({'success': False})


# 排序后端
def calculate_distance(lat1, lon1, lat2, lon2):  # 订单距离的计算
    # 将经纬度转换为弧度
    lat1 = radians(lat1)
    lon1 = radians(lon1)
    lat2 = radians(lat2)
    lon2 = radians(lon2)
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    distance = 6371 * c
    return distance

@csrf_exempt
def newest_orders(request):
    if request.method == "POST":
        data_list = []
        objects = Order.objects.order_by('start_time')[:3]
        for order in objects:
            data = {
                'id': order.id,
                'customer_id': order.customer_id,
                'price': order.price,
                'description': order.description,
                'type': order.type,
                'start_time': str(order.start_time)[:-6],
                'title': order.title,
                'date': order.date,
                'duration': order.duration,
            }
            data_list.append(data)
        return JsonResponse({'data': data_list})

@csrf_exempt
def newest_order(request):  # 按时间排序
    if request.method == "POST":
        latitude_2 = float(request.POST.get('latitude'))
        longitude_2 = float(request.POST.get('longitude'))
        data_list = []
        objects = Order.objects.order_by('start_time')[:3]
        for object in objects:
            latitude_1 = float(object.latitude)
            longitude_1 = float(object.longitude)
            distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
            distance = round(distance, 1)
            province, city, district = get_order_p_c_d(longitude_1, latitude_1)
            data = {
                'id': object.id,
                'customer_id': object.customer_id,
                'real_worker_id': object.real_worker_id,
                'condition': object.condition,
                'price': object.price,
                'description': object.description,
                'type': object.type,
                'start_time': object.start_time,
                'end_time': object.end_time,
                'title': object.title,
                'distance': distance,
                'province': province,
                'city': city,
                'district': district,
            }
            data_list.append(data)
        return JsonResponse({'success': True, 'data': data_list})
    else:
        return JsonResponse({'success': False})


def price_order(request):  # 按价格排序
    if request.method == "POST":
        latitude_2 = float(request.POST.get('latitude'))
        longitude_2 = float(request.POST.get('longitude'))
        data_list = []
        objects = Order.objects.order_by('price')[:5]
        for object in objects:
            latitude_1 = float(object.latitude)
            longitude_1 = float(object.longitude)
            distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
            distance = round(distance, 1)
            province, city, district = get_order_p_c_d(longitude_1, latitude_1)
            data = {
                'id': object.id,
                'customer_id': object.customer_id,
                'real_worker_id': object.real_worker_id,
                'condition': object.condition,
                'price': object.price,
                'description': object.description,
                'type': object.type,
                'start_time': object.start_time,
                'end_time': object.end_time,
                'title': object.title,
                'distance': distance,
                'province': province,
                'city': city,
                'district': district,
            }
            data_list.append(data)
        return JsonResponse({'success': True, 'data': data_list})
    else:
        return JsonResponse({'success': False})


def nearest_order(request):  # 按距离排序
    if request.method == "POST":
        latitude_2 = float(request.POST.get('latitude'))
        longitude_2 = float(request.POST.get('longitude'))
        print(latitude_2, longitude_2)
        data_list = []
        objects = Order.objects.order_by('price')
        for object in objects:
            latitude_1 = float(object.latitude)
            longitude_1 = float(object.longitude)
            distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
            distance = round(distance, 1)
            province, city, district = get_order_p_c_d(longitude_1, latitude_1)
            data = {
                'id': object.id,
                'customer_id': object.customer_id,
                'real_worker_id': object.real_worker_id,
                'condition': object.condition,
                'price': object.price,
                'description': object.description,
                'type': object.type,
                'start_time': object.start_time,
                'end_time': object.end_time,
                'title': object.title,
                'distance': distance,
                'province': province,
                'city': city,
                'district': district,
            }
            data_list.append(data)
        data_list = sorted(data_list, key=lambda x: x['distance'])[:5]
        print(data_list)
        return JsonResponse({'success': True, 'data': data_list})
    else:
        return JsonResponse({'success': False})


# 登录注册
@csrf_exempt
def image_code(request):  # 生成验证码图
    image_obj, code = check_code()
    request.session['image_code'] = code
    Code.objects.filter(id1=1).update(code_1=code)
    # print()
    request.session.set_expiry(60)
    stream = BytesIO()
    image_obj.save(stream, 'png')
    response = HttpResponse(stream.getvalue())
    response['clear'] = code
    print(code)
    return response


# 登录注册后端

@csrf_exempt
def log_in(request):  # 登录
    if request.method == "POST":
        # data = ''
        phone = request.POST.get('phone')
        print(phone)
        password = request.POST.get('password')
        print(password)
        user = models.UserInfo.objects.filter(phone=phone)
        if user:
            if user[0].password == password:
                verification_code = request.POST.get('verification_code')
                if verification_code != Code.objects.filter(id1=1).first().code_1:
                    return JsonResponse({'success': False, 'data': '验证码错误！'})
                else:
                    session_instance = models.Code.objects.filter(id1=3).first()
                    if session_instance:
                        session_instance.code_1 = user[0].id
                        session_instance.save()
                    return JsonResponse({'success': True, 'data': user[0].id})
            else:
                return JsonResponse({'success': False, 'data': '账号或密码错误!'})
        else:
            return JsonResponse({'success': False, 'data': '您未注册，请先注册.'})
    return JsonResponse({'success': False,'data': '网络错误'})
    # verification_code = request.POST.get('verification_code')
    #
    #
    #     if user_obj:
    #         for user_ob in user_obj:
    #             print(str(user_ob.password))
    #             if str(user_ob.password) != password:
    #                 user_obj = []
    #     print(user_obj)
    #
    #     if user_obj:
    #         if verification_code == Code.objects.filter(id1=1).first().code_1:
    #             request.session['user_name'] = user_name
    #             print(user_obj[0].id)
    #             return JsonResponse({'success': True, 'data': '登陆成功', 'user_id': user_obj[0].id})
    #         else:
    #             return JsonResponse({'success': True, 'data': '验证码错误'})
    #     else:
    #         return JsonResponse({'success': True, 'data': '用户名或密码错误'})
    #     print(data)
    #
    # else:
    #     return JsonResponse({'success': False})
    #


@csrf_exempt
def get_code(request):  # 添加短信发送的验证码获取
    if request.method == "POST":
        code = ''.join(random.choice('0123456789') for i in range(6))
        Code.objects.filter(id1=2).update(code_1=code)
        # 调用函数发送短信
        res = send_sms_single(int(request.POST.get('phone')), settings.TENCENT_SMS_TEMPLATE['register'], [code])
        print(res)
        return JsonResponse({'success': True, 'code': code})
    else:
        return JsonResponse({'success': False})


# distance筛选

def nearest_5(latitude_2, longitude_2):  # 五公里内
    data_list = []
    objects = Order.objects.all()
    for object in objects:
        latitude_1 = float(object.latitude)
        longitude_1 = float(object.longitude)
        distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
        distance = round(distance, 1)
        belief_score = UserInfo.objects.filter(id=object.customer_id).first().score
        province, city, district = get_order_p_c_d(longitude_1, latitude_1)
        data = {
            'id': object.id,
            'customer_id': object.customer_id,
            'real_worker_id': object.real_worker_id,
            'condition': object.condition,
            'price': float(object.price),
            'description': object.description,
            'type': object.type,
            'start_time': object.start_time,
            'end_time': object.end_time,
            'title': object.title,
            'date': object.date,
            'duration': object.duration,
            'score': object.score,
            'distance': distance,
            'requirement': object.requirement,
            'gender_requirement': object.gender_requirement,
            'belief_score': belief_score,
            'province': province,
            'city': city,
            'district': district,
        }
        data_list.append(data)
    data_list = [x for x in data_list if x['distance'] <= 5]
    return data_list


def nearest_10(latitude_2, longitude_2):  # 十公里内
    data_list = []
    objects = Order.objects.all()
    for object in objects:
        latitude_1 = float(object.latitude)
        longitude_1 = float(object.longitude)
        distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
        distance = round(distance, 1)
        belief_score = UserInfo.objects.filter(id=object.customer_id).first().score
        province, city, district = get_order_p_c_d(longitude_1, latitude_1)
        data = {
            'id': object.id,
            'customer_id': object.customer_id,
            'real_worker_id': object.real_worker_id,
            'condition': object.condition,
            'price': float(object.price),
            'description': object.description,
            'type': object.type,
            'start_time': object.start_time,
            'end_time': object.end_time,
            'title': object.title,
            'date': object.date,
            'duration': object.duration,
            'score': object.score,
            'distance': distance,
            'requirement': object.requirement,
            'gender_requirement': object.gender_requirement,
            'belief_score': belief_score,
            'province': province,
            'city': city,
            'district': district,
        }
        data_list.append(data)
    data_list = [x for x in data_list if x['distance'] <= 10]
    print(data_list)
    return data_list


def nearest_30(latitude_2, longitude_2):  # 三十公里内
    data_list = []
    objects = Order.objects.all()
    for object in objects:
        latitude_1 = float(object.latitude)
        longitude_1 = float(object.longitude)
        distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
        distance = round(distance, 1)
        belief_score = UserInfo.objects.filter(id=object.customer_id).first().score
        province, city, district = get_order_p_c_d(longitude_1, latitude_1)
        data = {
            'id': object.id,
            'customer_id': object.customer_id,
            'real_worker_id': object.real_worker_id,
            'condition': object.condition,
            'price': float(object.price),
            'description': object.description,
            'type': object.type,
            'start_time': object.start_time,
            'end_time': object.end_time,
            'title': object.title,
            'date': object.date,
            'duration': object.duration,
            'score': object.score,
            'distance': distance,
            'requirement': object.requirement,
            'gender_requirement': object.gender_requirement,
            'belief_score': belief_score,
            'province': province,
            'city': city,
            'district': district,
        }
        data_list.append(data)
    data_list = [x for x in data_list if x['distance'] <= 30]
    return data_list


def same_city(latitude_2, longitude_2):  # 同城
    data_list = []
    objects = Order.objects.all()
    for object in objects:
        latitude_1 = float(object.latitude)
        longitude_1 = float(object.longitude)
        distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
        distance = round(distance, 1)
        belief_score = UserInfo.objects.filter(id=object.customer_id).first().score
        province, city, district = get_order_p_c_d(longitude_1, latitude_1)
        data = {
            'id': object.id,
            'customer_id': object.customer_id,
            'real_worker_id': object.real_worker_id,
            'condition': object.condition,
            'price': float(object.price),
            'description': object.description,
            'type': object.type,
            'start_time': object.start_time,
            'end_time': object.end_time,
            'title': object.title,
            'date': object.date,
            'duration': object.duration,
            'score': object.score,
            'distance': distance,
            'requirement': object.requirement,
            'gender_requirement': object.gender_requirement,
            'belief_score': belief_score,
            'province': province,
            'city': city,
            'district': district,
        }
        data_list.append(data)
    data_list = [x for x in data_list if x['distance'] <= 50]
    return data_list


def distance_filter(latitude_2, longitude_2, dis_info, data_list):
    if dis_info == '':
        objects = Order.objects.all()
        for object in objects:
            latitude_1 = float(object.latitude)
            longitude_1 = float(object.longitude)
            distance = calculate_distance(latitude_1, longitude_1, latitude_2, longitude_2)
            distance = round(distance, 1)
            belief_score = UserInfo.objects.filter(id=object.customer_id).first().score
            province, city, district = get_order_p_c_d(longitude_1, latitude_1)
            data = {
                'id': object.id,
                'customer_id': object.customer_id,
                'real_worker_id': object.real_worker_id,
                'condition': object.condition,
                'price': float(object.price),
                'description': object.description,
                'type': object.type,
                'start_time': object.start_time,
                'end_time': object.end_time,
                'title': object.title,
                'date': object.date,
                'duration': object.duration,
                'score': object.score,
                'distance': distance,
                'requirement': object.requirement,
                'gender_requirement': object.gender_requirement,
                'belief_score': belief_score,
                'province': province,
                'city': city,
                'district': district,
            }
            data_list.append(data)
        return data_list
    if dis_info == "5km内":
        data_list = nearest_5(latitude_2, longitude_2)
        return data_list
    elif dis_info == "10km内":
        data_list = nearest_10(latitude_2, longitude_2)
        return data_list
    elif dis_info == "30km内":
        data_list = nearest_30(latitude_2, longitude_2)
        return data_list
    else:
        data_list = same_city(latitude_2, longitude_2)
        return data_list


# 年龄要求筛选
def age_filter(data_list, age_info):
    datalist = []
    if age_info == '':
        return data_list
    if age_info == '大学生':
        for data in data_list:
            if data['requirement'] == '大学生':
                datalist.append(data)
        return datalist
    if age_info == '22岁以上':
        for data in data_list:
            if data['requirement'] == '22岁以上':
                datalist.append(data)
        return datalist
    if age_info == '30岁以上':
        for data in data_list:
            if data['requirement'] == '30岁以上':
                datalist.append(data)
        return datalist
    if age_info == '40岁以上':
        for data in data_list:
            if data['requirement'] == '40岁以上':
                datalist.append(data)
        return datalist


# 性别要求筛选
def gender_filter(data_list, gender_info):
    datalist = []
    if gender_info == '':
        return data_list
    if gender_info == '男':
        for data in data_list:
            if data['gender_requirement'] == '男':
                datalist.append(data)
        return datalist
    if gender_info == '女':
        for data in data_list:
            if data['gender_requirement'] == '女':
                datalist.append(data)
        return datalist


# 时薪要求筛选
def hourly_wage_filter(data_list, min_hourly_wage, max_hourly_wage):
    datalist = []
    if (min_hourly_wage == '') | (max_hourly_wage == ''):
        return data_list
    for data in data_list:
        if (data['price'] >= int(min_hourly_wage)) & (data['price'] <= int(max_hourly_wage)):
            datalist.append(data)
    return datalist


# 类型筛选
def type_filter(data_list, type_info):
    datalist = []
    if type_info == '':
        return data_list
    if type_info == '带宠':
        for data in data_list:
            if data['type'] == '带宠':
                datalist.append(data)
        return datalist
    if type_info == '带娃':
        for data in data_list:
            if data['type'] == '带娃':
                datalist.append(data)
        return datalist
    if type_info == '收纳师':
        for data in data_list:
            if data['type'] == '收纳师':
                datalist.append(data)
        return datalist


# 时长筛选
def duration_filter(data_list, duration_info):
    datalist = []
    if duration_info == '':
        return data_list
    if duration_info == '半天以内':
        for data in data_list:
            data_duration = float(data['duration'].split('h')[0])
            if data_duration <= 12:
                datalist.append(data)
        return datalist
    if duration_info == '一天以内':
        for data in data_list:
            data_duration = float(data['duration'].split('h')[0])
            if data_duration <= 24:
                datalist.append(data)
        return datalist
    if duration_info == '三天以内':
        for data in data_list:
            data_duration = float(data['duration'].split('h')[0])
            if data_duration <= 72:
                datalist.append(data)
        return datalist
    if duration_info == '三天以上':
        for data in data_list:
            data_duration = float(data['duration'].split('h')[0])
            if data_duration > 72:
                datalist.append(data)
        return datalist


# 工作日期筛选
def work_day_filter(data_list, work_day_info):
    datalist = []
    current_date = datetime.now()
    current_year = current_date.year
    current_month = current_date.month
    current_day = current_date.day
    print(current_year, current_month, current_day)
    if work_day_info == '':
        return data_list
    if work_day_info == '仅看当天':
        for data in data_list:
            date_list = data['date'].split(',')
            if (current_year == int(date_list[0])) & (current_month == int(date_list[1])) & (
                    current_day == int(date_list[2])):
                datalist.append(data)
        return datalist
    elif work_day_info == '仅看周末':
        for data in data_list:
            date_list = data['date'].split(',')
            date = datetime(int(date_list[0]), int(date_list[1]), int(date_list[2]))
            if date.isoweekday() in (6, 7):
                datalist.append(data)
        return datalist
    else:
        date_list_1 = work_day_info.split('-')
        date_1 = datetime(int(date_list_1[0]), int(date_list_1[1]), int(date_list_1[2]))
        for data in data_list:
            date_list_2 = data['date'].split(',')
            date_2 = datetime(int(date_list_2[0]), int(date_list_2[1]), int(date_list_2[2]))
            if date_1 == date_2:
                datalist.append(data)
        return datalist


# 根据地理位置筛选
def pcd_filter(data_list, province, city, district):
    datalist = []
    datalist_2 = []
    datalist_3 = []
    some_province = ['北京市', '上海市', '重庆市', '天津市']
    # print(province)
    if province != '':
        for data in data_list:
            if province == data['province']:
                datalist.append(data)
        if province in some_province:
            if district != '':
                for data in datalist:
                    if district == data['district']:
                        datalist_2.append(data)
                return datalist_2
            else:
                return datalist
        elif city != '':
            for data in datalist:
                if city == data['city']:
                    datalist_2.append(data)
            if district != '':
                for data in datalist_2:
                    if district == data['district']:
                        datalist_3.append(data)
                return datalist_3
            else:
                return datalist_2
        elif city == '':
            return datalist
    else:
        now_province, now_city = get_now_p_c()
        if now_city != '':
            for data in data_list:
                if now_province == data['province']:
                    datalist.append(data)
            if province in some_province:
                for data in datalist:
                    if now_city == data['city']:
                        datalist_2.append(data)
                return datalist_2
        else:
            for data in data_list:
                if now_province == data['province']:
                    datalist.append(data)
            return datalist


# 按照薪资排序
def wage_sort(data_list, sorted_info):
    if sorted_info == '':
        return data_list
    if sorted_info == '时薪由高到低':
        datalist = sorted(data_list, key=lambda x: x['price'], reverse=True)
        return datalist
    if sorted_info == '总薪由高到低':
        for data in data_list:
            duration = int(data['duration'].split('h')[0])
            all_wage = duration * data['price']
            data['all_wage'] = float(all_wage)
        datalist = sorted(data_list, key=lambda x: x['all_wage'], reverse=True)
        return datalist


# 按照评分排序
def score_sort(data_list, sorted_info):
    if sorted_info == '':
        return data_list
    if sorted_info == '信誉分由高到低':
        datalist = sorted(data_list, key=lambda x: x['belief_score'], reverse=True)
        return datalist
    if sorted_info == '评价分由高到低':
        datalist = sorted(data_list, key=lambda x: x['score'], reverse=True)
        return datalist


# 按照距离排序
def distance_sort(data_list, sorted_info):
    if sorted_info == '':
        return data_list
    if sorted_info == '由远到近':
        datalist = sorted(data_list, key=lambda x: x['distance'], reverse=True)
        return datalist
    if sorted_info == '由近到远':
        datalist = sorted(data_list, key=lambda x: x['distance'])
        return datalist


# 按照时长排序
def duration_sort(data_list, sorted_info):
    if sorted_info == '':
        return data_list
    if sorted_info == '由长至短':
        datalist = sorted(data_list, key=lambda x: int(x['duration'].split('h')[0]), reverse=True)
        return datalist
    if sorted_info == '由短至长':
        datalist = sorted(data_list, key=lambda x: int(x['duration'].split('h')[0]))
        return datalist


# 总排序筛选函数
@csrf_exempt
def sort_and_filter(request):
    if request.method == "POST":
        latitude = float(request.POST.get('latitude'))
        longitude = float(request.POST.get('longitude'))
        distance_info = request.POST.get('distance_info')
        age_info = request.POST.get('age_info')
        gender_info = request.POST.get('gender_info')
        type_info = request.POST.get('type_info')
        duration_info = request.POST.get('duration_info')
        work_date_info = request.POST.get('work_date_info')
        max_hour_wage = request.POST.get('max_hour_wage')
        min_hour_wage = request.POST.get('min_hour_wage')
        wage_order_info = request.POST.get('wage_order_info')
        rate_order_info = request.POST.get('rate_order_info')
        distance_order_info = request.POST.get('distance_order_info')
        duration_order_info = request.POST.get('duration_order_info')
        province = request.POST.get('province')
        city = request.POST.get('city')
        district = request.POST.get('district')
        data_list = []
        data_list = distance_filter(latitude, longitude, distance_info, data_list)
        data_list = age_filter(data_list, age_info)
        data_list = gender_filter(data_list, gender_info)
        data_list = type_filter(data_list, type_info)
        data_list = duration_filter(data_list, duration_info)
        data_list = work_day_filter(data_list, work_date_info)
        data_list = hourly_wage_filter(data_list, min_hour_wage, max_hour_wage)
        data_list = wage_sort(data_list, wage_order_info)
        data_list = score_sort(data_list, rate_order_info)
        data_list = distance_sort(data_list, distance_order_info)
        data_list = duration_sort(data_list, duration_order_info)
        data_list = pcd_filter(data_list, province, city, district)
        print(data_list)
        if not data_list:
            return JsonResponse({'success': True, 'data': []})
        datalist = []
        for data in data_list:
            data_new = {
                'id': data['id'],
                'title': data['title'],
                'customer_id': data['customer_id'],
                'description': data['description'],
                'type': data['type'],
                'price': data['price'],
                'start_time': data['start_time']
            }
            datalist.append(data_new)
        print(datalist)
        return JsonResponse({'success': True, 'data': datalist})
    else:
        return JsonResponse({'success': False})
